<?php


namespace app\api\controller;


use app\api\BaseApi;
use app\service\TaskService;
use app\service\UserService;
use think\response\Json;

class Task extends BaseApi
{


    /**
     * 领取任务
     */
    public function getMyTask() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', '100104-01');
        }
        $task_id = trim(input('task_id'));
        if (empty($task_id)) {
            return $this->error('参数错误', '', '100104-02');
        } else {
            if (floor($task_id) != $task_id) {
                return $this->error('参数错误', '', '100104-03');
            }
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', '100104-04');
        }
        //当天可以领取的任务数量
        $canGetTaskCount = $this ->getVipTaskCount($userInfo['data']['vip_lv']);
        /*
        $price = 0;
        $validDayCount = 365;
        if($userInfo['data']['vip_lv'] ==0){
            $canGetTaskCount = 1;
            $price = 1.7;
        }elseif($userInfo['data']['vip_lv'] ==1){
            $canGetTaskCount = 9;
            $price = 1.7;
        }elseif($userInfo['data']['vip_lv'] ==2){
            $canGetTaskCount = 26;
            $price = 1.7;
        }elseif($userInfo['data']['vip_lv'] ==3){
            $canGetTaskCount = 65;
            $price = 1.7;
        }elseif($userInfo['data']['vip_lv'] ==4){
            $canGetTaskCount = 60;
            $price = 3.2;
        }elseif($userInfo['data']['vip_lv'] ==5){
            $canGetTaskCount = 90;
            $price = 3.2;
        }elseif($userInfo['data']['vip_lv'] ==6){
            $canGetTaskCount = 75;
            $price = 5.6;
        }elseif($userInfo['data']['vip_lv'] ==7){
            $canGetTaskCount = 110;
            $price = 5.6;
        }
        */

        $taskService = new TaskService();
        $result = $taskService->insertMyTask($userInfo['data']['id'], $task_id,$canGetTaskCount);
        if ($result['status'] == 1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'], '', '100104-05');
        }
    }


    /**
     * 查询某个用户的某个任务信息
     */
    public function getMyTaskByTaskId() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $task_id = trim(input('task_id'));
        if (empty($task_id)) {
            return $this->error('参数错误', '', '100104-02');
        } else {
            if (floor($task_id) != $task_id) {
                return $this->error('参数错误', '', '100104-03');
            }
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $taskService = new TaskService();
        $result = $taskService->getUserTaskByTaskIDAndUserID($userInfo['data']['id'], $task_id);
        if ($result['status'] == 1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'], '', '100104-05');
        }
    }

    /**
     * 首页任务列表 默认5
     */
    public function myTaskList() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'],$userInfo['data']);
        }

        $status = trim(input('status'));
        if (empty($status)) {
            $status = 1;
        } else {
            if (floor($status) == $status) {
                if ($status > 4) {
                    return $this->error('参数错误', '', '100104-07');
                }
            } else {
                return $this->error('参数错误', '', '100104-08');
            }
        }
        $str_time = trim(input('str_time'));//任务领取的时间
        $page = trim(input('page'));
        $size = trim(input('size'));

        //查出任务 用户任务列表
        $taskService = new TaskService();
        $userTaskInfo = $taskService->getUserTaskByUserId($userInfo['data']['id'], $status, $str_time,$page,$size);
        if ($userTaskInfo['status'] == 0) {
            return $this->error($userTaskInfo['msg'], '', '100104-09');
        } else {
            foreach ($userTaskInfo['data'] as $key => &$value){
                $task_type_name = '';
                //var_dump($value);die();
                switch ($value['task_type'])
                {
                    case '101':
                        $task_type_name = '微视';
                        break;
                    case '201':
                        $task_type_name = '小红书';
                        break;
                    case '301':
                        $task_type_name = '快手';
                        break;
                    case '401':
                        $task_type_name = '抖音';
                        break;
                    default:
                        $task_type_name = '未知';
                        break;
                }
                $value['task_type_name'] = $task_type_name;
            }
            return $this->success('成功', $userTaskInfo['data']);
        }
    }

    /**
     * 任务详情
     */
    public function taskDetail() : Json {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $task_id = trim(input('task_id'));
        if (empty($task_id)) {
            return $this->error('参数错误','', '100104-11');
        } else {
            if (floor($task_id) != $task_id) {
                return $this->error('参数错误','', '100104-12');
            }
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'],'', $userInfo['data']);
        }
        $taskService = new TaskService();
        $result = $taskService->getTaskDetailByTaskID($task_id);
        if ($result['status'] == 1) {
            $user_id = $userInfo['data']['id'];
            $my_task_status = '0';
            $thisMyTask = $taskService -> getTaskDetailByTaskIDAndUserID($user_id,$task_id);
            if($thisMyTask['status'] == 1 && !empty($thisMyTask['data'])){
                $my_task_status = $thisMyTask['data']['task_status'];
            }
            $task_status_text ='任务进行中'; //任务状态 0:可用 1:任务次数已用完
            if($result['data']['task_status'] == 1){
                $task_status_text ='任务次数已用完';
            }
            $result['data']['task_status_text'] =  $task_status_text; //转化一下状态名称
            $result['data']['my_task_status'] = $my_task_status;
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'],'', '100104-14');
        }
    }


    /**
     * 用户提交完成任务的数据
     */
    public function commitUserTaskData(): Json{
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问','', $this::ERROR_CODE);
        }
        $task_id = trim(input('task_id'));
        if (empty($task_id)) {
            return $this->error('参数错误','', '100104-16');
        } else {
            if (floor($task_id) != $task_id) {
                return $this->error('参数错误','', '100104-17');
            }
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'],'',$userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $remark = trim(input('remark'));
        $pics = trim(input('pics'));


        $filename_url = '';
        if(!empty($pics)){
            $file_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'.date("Ymd").'/'.$user_id;
            $dir = iconv("UTF-8", "GBK",$file_path);
            if (!file_exists($dir)) {
                $r =  mkdir($file_path, 0777, true);
                //创建时间文件夹
                if(!$r){
                    return $this->error('创建文件夹失败','', '100104-18');
                }
            }
            $pics_base = json_decode($pics,true);
            //return $this->error($pics_base, '100104-18');
            if(count($pics_base) > 3){
                return $this->error('凭证图片最多只用上传3个即可','', '100104-18-03');
            }
            foreach ($pics_base as $key =>$value){
                $arr = preg_split("/(,|;)/",$value);//分隔三部分，data:image/png  base64  后面一堆
                if(count($arr) != 3){
                    return $this->error('Base64图片数据格式严重错误,程序终止执行','', '100104-18-02');
                    die();
                }
                $base64Data = $arr[2];
                $arr2 = explode('/',$arr[0]);      //分割出图片格式
                $file_type = $arr2[1];
                //var_dump($img);

                $img_name = $this -> getFileName();
                $filename_url = '/upload/'.date("Ymd").'/'.$user_id.'/'.$img_name.'.'.$file_type.';'.$filename_url;
                $filename = $file_path.'/'.$img_name.'.'.$file_type;
                //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
                $filename = iconv("UTF-8","gb2312",$filename);
                //var_dump($filename);die();
                //检查文件是否存在
                if(file_exists($filename)) {
                    return $this->error('已存在同名文件请重新上传','', '100105-18-01');
                }
                $img = base64_decode($base64Data);
                $upload_result = file_put_contents($filename, $img);//返回的是字节数
            }
        }
        $taskService = new TaskService();
        $result = $taskService->commitUserTaskData($user_id, $task_id,$filename_url,$remark);
        if ($result['status'] == 1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'],'', '100104-19');
        }
    }

}